package com.ye.controller;

import com.ye.domain.Music;
import com.ye.domain.R;
import com.ye.service.MusicService;
import jdk.swing.interop.SwingInterOpUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;


@RestController
@RefreshScope
@RequestMapping("/music")

public class MusicUploadController {
    private static final String[] FILE_TYPE_PIC = {".jpg", ".jpeg", ".png"};
    private static final String[] FILE_TYPE_AUDIO = {".mp3", ".mp4"};
    @Autowired
    private MusicService musicService;

    @PostMapping("/uploadMusic")

    public R uploadMusic(@RequestParam("file") MultipartFile[] file, @RequestParam("singer") String singer) {

        String audioRemotePath = null;
        String picRemotePath = null;
        Music music = new Music();


        for (MultipartFile multipartFile : file) {
//            获取文件实际名称
            String originalFilename = multipartFile.getOriginalFilename();
//            截取后缀进行上传类型的判断
            assert originalFilename != null;
            int i = originalFilename.indexOf(".");
            String suffix = originalFilename.substring(i, originalFilename.length());
            System.out.println(suffix);


            for (String type : FILE_TYPE_AUDIO) {

                File temporary = new File(originalFilename);
                try {
//                    multipartFile转File
                    FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), temporary);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (suffix.equals(type)) {
                    audioRemotePath = musicService.uploadMusic(originalFilename, temporary, 1);
                    music.setSongName(originalFilename);
                    music.setSongUrl(audioRemotePath);

                } else {
//                    System.out.println("文件为图片");

                    picRemotePath = musicService.uploadMusic(originalFilename, temporary, 2);

                    music.setPicUrl(picRemotePath);
                }
                temporary.delete();
                break;

            }

        }

        if (singer!= null&&singer.length()>0) {
            music.setSinger(singer);
        }

        if (audioRemotePath != null) {
            musicService.saveMusicFromOss(music);
        }


        HashMap<String, String> hp = new HashMap<>();
        if (audioRemotePath != null) {
            hp.put("audioUrl", audioRemotePath);
        }
        if (picRemotePath != null) {
            hp.put("imgUrl", picRemotePath);
        }

        return R.ok(hp).count(hp.size());
    }
}
